#include <SPI.h>
#include <RCSwitch.h>
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#ifndef STASSID
#define STASSID "SSID"    //修改为你的wifi名称
#define STAPSK "password" //修改为你的wifi密码
#endif
const char *ssid = STASSID;
const char *password = STAPSK;
RCSwitch mySwitch433 = RCSwitch();
const char *server = "192.168.1.10"; //修改为你的mqtt服务器地址
WiFiClient Client;
PubSubClient mqttClient(Client);
boolean ResponseBegin = false;
void setup()
{
  pinMode(D8, OUTPUT);            //D8号引脚为正极
  digitalWrite(D8, LOW);          //未发送信号时拉低电平防止干扰其他遥控器
  mySwitch433.enableTransmit(D2); //输出端口为D2
  Serial.begin(115200);
  mqttClient.setServer(server, 1883);       //设置MQTT服务器
  mqttClient.setCallback(subscribeReceive); //设置收到订阅信息后的回调函数
  //初始化网络服务
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void loop()
{
  delay(2000);
  //服务器连接失败时重建连接
  if (!mqttClient.connected())
  {
    reconnect();
  }
  mqttClient.loop();
}
void reconnect()
{
  while (!mqttClient.connected())
  {
    Serial.print("Attempting MQTT connection...");
    if (mqttClient.connect("myClientID", "username", "password")) //修改为你的mqtt服务器账号密码
    {
      Serial.println("connected");
      mqttClient.publish("Home/RF/433/status", "MQTT2RF433_Standby");
      mqttClient.subscribe("Home/RF/433/send");
    }
    else
    {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println("try again in 5 seconds");
      delay(5000);
    }
  }
}
void subscribeReceive(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  String returnValue = "";
  for (int i = 0; i < length; i++)
  {
    returnValue += char(payload[i]);
  }
  Serial.println("RF:" + returnValue);
  action(returnValue);
}
void action(String key)
{
  mqttClient.publish("Home/RF/433/status", key.c_str());
  digitalWrite(D8, HIGH);
  mySwitch433.send(key.toInt(), 24);
  digitalWrite(D8, LOW);
}
